<template>
  <div v-if="giveRule" class="give-config">
    <div v-loading="loading" class="app-main-content-box form" element-loading-text="修改中">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
        <!-- 启用按钮 -->
        <el-form-item label="启用赠送功能：">
          <el-switch v-model="form.enableGive" />
        </el-form-item>
        <el-form-item>
          <el-collapse-transition>
            <el-card v-if="form.enableGive">

              <el-form-item label="可附赠余额：">
                <el-switch v-model="form.enableExtraBalance" />
                <el-collapse-transition>
                  <el-card v-if="form.enableExtraBalance" shadow="never">
                    <div style="margin-bottom:18px"> <el-tag>附赠金额暂时只仅支持商户后台赠送，顾客小程序赠送时不支持选择附赠金额</el-tag></div>
                    <el-form-item label="可选赠送金额：">
                      <div
                        v-for="(item,index) in form.defaultAmount"
                        :key="index"
                        class="give-balance-val app-border-color-primary"
                      >
                        <span>{{ item/100 }}元</span>
                        <i class="el-icon-close" @click="delGiveBalance(index)" />
                      </div>
                      <el-button
                        type="primary"
                        icon="el-icon-plus"
                        size="small"
                        circle
                        @click="addGiveBalance"
                      />
                    </el-form-item>
                    <el-form-item label="可自定义金额：">
                      <el-switch v-model="form.enableAnyAmount" />
                    </el-form-item>
                    <div v-if="balanceTips" class="balance-tips app-text-color-danger">请至少设置一种赠送余额方式</div>
                  </el-card>
                </el-collapse-transition>
              </el-form-item>
              <!-- <el-form-item label="结账付款方式：" prop="payChannel">
                <el-checkbox-group v-model="form.payChannel">
                  <el-checkbox label="1" name="payChannel">微信支付</el-checkbox>
                  <el-checkbox label="2" name="payChannel">会员余额支付</el-checkbox>
                </el-checkbox-group>
              </el-form-item> -->
              <!-- 过期时间 -->
              <el-form-item label="最晚领取时间：" prop="expireHours">
                <el-radio v-model="form.expireHours" :label="24">24小时，超过时间自动过期并把付款金额原路退回顾客</el-radio>
                <br>
                <el-radio v-model="form.expireHours" :label="48">48小时，超过时间自动过期并把付款金额原路退回顾客</el-radio>
                <br>
                <el-radio v-model="form.expireHours" :label="72">72小时，超过时间自动过期并把付款金额原路退回顾客</el-radio>
              </el-form-item>
            </el-card>
          </el-collapse-transition>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round @click="onSubmit">保 存</el-button>
          <el-button round @click="initData()">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { updateGiveVipCardRule } from '@/api/vip'
export default {
  props: {
    giveRule: {
      type: Object,
      require: true
    },
    tabName: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        // payChannel: [
        //   {
        //     type: "array",
        //     required: true,
        //     message: "请至少选择一种赠送支付方式",
        //     trigger: "change"
        //   }
        // ],
        expireHours: [
          {
            required: true,
            message: '请选择最晚领取时间',
            trigger: 'change'
          }
        ]
      },
      // 状态
      loading: false,
      balanceTips: false,
      // 数据
      form: {
        enableGive: true, // 是否可以赠送
        enableExtraBalance: false, // 是否可以赠送余额
        enableAnyAmount: false, // 是否可以自定义赠送余额
        defaultAmount: [], // 可以赠送的余额
        expireHours: '' //  过期时间退款
        // payChannel: ["1"] // 赠送支付方式
      }
    }
  },
  watch: {
    tabName(val) {
      if (val === 'config') {
        this.initData()
      }
    },
    giveRule: {
      handler: function(val) {
        this.form = JSON.parse(JSON.stringify(this.giveRule))
      }
    },
    form: {
      handler: function(val) {
        if (val.enableGive && val.enableExtraBalance) {
          if (!val.enableAnyAmount && val.defaultAmount.length === 0) {
            this.balanceTips = true
          } else {
            this.balanceTips = false
          }
        }
      },
      deep: true
    }
  },

  mounted() {
    this.form = JSON.parse(JSON.stringify(this.giveRule))
  },

  methods: {
    /**
       *  按钮组
       */
    // 保存新配置
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid && !this.balanceTips) {
          if (!this.form.enableExtraBalance) {
            this.form.enableAnyAmount = false
            this.defaultAmount = []
          }
          const data = JSON.parse(JSON.stringify(this.form))
          data.defaultAmount =
              data.defaultAmount === [] ? '' : data.defaultAmount.join(',')
          // data.payChannel = data.payChannel.join(",");
          this.loading = true
          updateGiveVipCardRule(data)
            .then(res => {
              this.initData()
              this.loading = false
              this.$notify({
                title: '成功',
                message: '赠送规则已成功变更',
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .catch(err => {
              this.loading = false
            })
        }
      })
    },

    // 增加可赠送金额
    addGiveBalance() {
      this.$prompt('', '请输入可赠送余额(元)', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(([1-9][0-9]*)|(0\.(0[1-9]|[1-9][0-9]{0,1}))|([1-9][0-9]*\.\d{1,2}))$/,
        inputErrorMessage:
            '输入不符规则,请输入正整数，正小数（小数位不超过2位）'
      })
        .then(({ value }) => {
          this.form.defaultAmount.push(this.$math.mul(value, 100, 0))
          // 去重
          this.form.defaultAmount = [...new Set(this.form.defaultAmount)]
        })
        .catch(err => {})
    },

    // 删除可赠送金额
    delGiveBalance(index) {
      this.form.defaultAmount.splice(index, 1)
    },

    // 刷新规则数据
    initData() {
      this.$emit('getGiveRule')
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .give-config {
    .form {
      .give-balance-val {
        position: relative;
        display: inline-block;
        height: 30px;
        padding: 0 5px 0 10px;
        margin-right: 10px;
        margin-bottom: 5px;
        border-width: 1px;
        border-style: solid;
        border-radius: 5px;
        line-height: 30px;
        font-size: 14px;
        color: $dark-font-color;
        .el-icon-close {
          cursor: pointer;
        }
      }
      .balance-tips {
        height: 22px;
        line-height: 22px;
        font-size: 12px;
      }
    }
  }
</style>
